import 'package:flutter/material.dart';
import 'package:english_words/english_words.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final wordPair = new WordPair.random();
    return new MaterialApp(
      title: 'Words List',
      theme: new ThemeData.dark(),
      home: new RandowWords(),
    );
  }
}

class RandowWords extends StatefulWidget {
  const RandowWords({Key? key}) : super(key: key);

  @override
  _RandowWordsState createState() => _RandowWordsState();
}

class _RandowWordsState extends State<RandowWords> {
  //  单词列表
  final _wordList = <WordPair>[];
//  收藏列表
  final _saveList = new Set<WordPair>();
  //  单词文字样式
  final _fontStyle = const TextStyle(fontSize: 18.0, color: Colors.green);
  // 导航栏菜单按钮点击事件
  void _toSaveList() {
    Navigator.of(context).push(
      new MaterialPageRoute(
        builder: (context) {
          final tiles = _saveList.map((pair) {
            return new ListTile(
              title: new Text(
                pair.asPascalCase,
                style: _fontStyle,
              ),
            );
          });
          final divided = ListTile.divideTiles(
            tiles: tiles,
            context: context,
          ).toList();
          return new Scaffold(
            appBar: new AppBar(
              title: new Text('收藏列表'),
            ),
            body: new ListView(children: divided,),
          );
        }
      )
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new AppBar(
        title: new Text('Words List'),
        actions: <Widget>[
          new IconButton(onPressed: _toSaveList, icon: new Icon(Icons.list))
        ],
      ),
      body: _buildwordList(),
    );
  }

  Widget _buildwordList() {
    return new ListView.builder(
      padding: new EdgeInsets.all(16.0),
      // 对于每个单词对都会调用一次itemBuilder，然后将单词对添加到ListTile行中
      itemBuilder: (context, i) {
        // 在奇数行，添加一个1像素高分割线widget，来分隔相邻的词对
        if(i.isOdd) return new Divider();
        // 语法 "i ~/ 2" 表示i除以2，但返回值是整形（向下取整）
        final index = i ~/ 2;
        // 当前为单词列表中最后一个时，重新添加10条
        if(index >= _wordList.length) {
          _wordList.addAll(generateWordPairs().take(10));
        }
        return _buildRow(_wordList[index]);
      },
    );
  }

  Widget _buildRow(WordPair pair) {
    // 判断当前单词是否为收藏单词
    final alreadySaved = _saveList.contains(pair);
    return ListTile(
      title: new Text(
        pair.asPascalCase,
        style: _fontStyle,
      ),
      trailing: new Icon(
        alreadySaved?Icons.favorite:Icons.favorite_border,
        color: alreadySaved?Colors.red:null,
      ),
      onTap: () {
        setState(() {
          if(alreadySaved) {
            _saveList.remove(pair);
          }else {
            _saveList.add(pair);
          }
        });
      },
    );
  }
}

